const { log, Message } = require("wechaty");
const PUPPET = require("wechaty-puppet");
const dayjs = require("dayjs");
const fs = require("fs");
const { getCate, getCateList, getPrice } = require("./apis/sellingMembership");
const { setCache, getCache } = require("./utils/cache");
const { conversation } = require("./chat");
const LOGPRE = "[终端打印日志]";

async function getMessagePayload(message) {
  switch (message.type()) {
    case PUPPET.types.Message.Text:
      log.silly(LOGPRE, `get message text: ${message.text()}`);
      break;

    case PUPPET.types.Message.Attachment:
    case PUPPET.types.Message.Audio: {
      const attachFile = await message.toFileBox();

      const dataBuffer = await attachFile.toBuffer();

      log.info(LOGPRE, `get message audio or attach: ${dataBuffer.length}`);

      break;
    }

    case PUPPET.types.Message.Video: {
      const videoFile = await message.toFileBox();

      const videoData = await videoFile.toBuffer();

      log.info(LOGPRE, `get message video: ${videoData.length}`);

      break;
    }

    case PUPPET.types.Message.Emoticon: {
      const emotionFile = await message.toFileBox();

      const emotionJSON = emotionFile.toJSON();
      log.info(
        LOGPRE,
        `get message emotion json: ${JSON.stringify(emotionJSON)}`
      );

      const emotionBuffer = await emotionFile.toBuffer();

      log.info(LOGPRE, `get message emotion: ${emotionBuffer.length}`);

      break;
    }

    case PUPPET.types.Message.Image: {
      const messageImage = await message.toImage();

      const thumbImage = await messageImage.thumbnail();
      const thumbImageData = await thumbImage.toBuffer();

      log.info(LOGPRE, `get message image, thumb: ${thumbImageData.length}`);

      const hdImage = await messageImage.hd();
      const hdImageData = await hdImage.toBuffer();

      log.info(LOGPRE, `get message image, hd: ${hdImageData.length}`);

      const artworkImage = await messageImage.artwork();
      const artworkImageData = await artworkImage.toBuffer();

      log.info(
        LOGPRE,
        `get message image, artwork: ${artworkImageData.length}`
      );

      break;
    }

    case PUPPET.types.Message.Url: {
      const urlLink = await message.toUrlLink();
      log.info(LOGPRE, `get message url: ${JSON.stringify(urlLink)}`);

      const urlThumbImage = await message.toFileBox();
      const urlThumbImageData = await urlThumbImage.toBuffer();

      log.info(LOGPRE, `get message url thumb: ${urlThumbImageData.length}`);

      break;
    }

    case PUPPET.types.Message.MiniProgram: {
      const miniProgram = await message.toMiniProgram();

      log.info(LOGPRE, `MiniProgramPayload: ${JSON.stringify(miniProgram)}`);

      break;
    }
  }
}

async function dingDongBot(message) {
  if (message.to()?.self() && message.text().indexOf("ding") !== -1) {
    await message.talker().say(message.text().replace("ding", "dong"));
  }
}

//处理会员消息
async function sellingMembership(message) {
  try {
    //如果来自群聊消息
    if (message.to().type()=== "group") return;
    // 如果是自己给自己发送的消息，则忽略或进行其他处理
    if (message.from().id === message.to().id) return;
    if (message.text().indexOf("微信") !== -1) return;
    if (message.to()?.self() && message.text().indexOf("会员") !== -1) {
      let data = getCache("Membership.json", "getCate");
      if (!data) {
        data = await getCate();
        setCache("Membership.json", "getCate", data, 86400);
        console.log(data, "我来自getCate接口data-");
      } else {
        console.log(data, "我来自getCate缓存data-");
      }
      let str = "";
      data.cate.forEach((item) => {
        str += item.name + `\n-----序号-${item.id}\n\n`;
      });
      await message
        .talker()
        .say(
          `会员信息如下,请回复对应序号，进行查询---\n\n请按格式询问哦\n${str}`
        );
    }
    if (
      message.to()?.self() &&
      (message.text().indexOf("[序号]") !== -1 ||
        !isNaN(parseInt(message.text())))
    ) {
      const catchKey = message.text();
      let data = getCache("Membership.json", catchKey);
      if (!data) {
        const cateId = catchKey.split("-")[1] || parseInt(message.text());
        console.log(cateId, "cateId--");
        const res = await getCateList(cateId);
        data = await getMoneyGoods(res);
        setCache("Membership.json", catchKey, data, 86400);
        console.log(data, "我来自getCateList接口data-");
      } else {
        console.log(data, "我来自getCateList缓存data-");
      }
      let str = "";
      data.list.forEach((item) => {
        str +=
          item.name +
          `\n---[售价]${item.price}\n---[已售]${item.sales}\n---[库存]${item.stock}\n\n`;
      });
      await message.talker().say(`${data.info.name}\n\n${str}`);
    }
    // if (message.to()?.self() && message.text("机器喵")) {
    //   return message
    //     .talker()
    //     .say(
    //       `你好,叮当机器喵,为您服务\n输入[会员]查询全部商品-----\n\n输入对应序号查询详细价格-----\n\n[序号]+转账进行购买-----`
    //     );
    // }
  } catch (error) {
    return message
      .talker()
      .say(
        `你好,叮当机器喵,为您服务\n输入[会员]查询全部商品-----\n\n输入对应序号查询详细价格-----\n\n[序号]+转账进行购买-----`
      );
  }
}

//处理智能机器人对话
async function chatGpt(message) {
  //如果来自群聊消息
  if (message.to().type()=== "group") return;
  // 如果是自己给自己发送的消息，则忽略或进行其他处理
  if (message.from().id === message.to().id) return;
  if (message.text().indexOf("微信") !== -1) return;
  if (message.to()?.self() && message.text()) {
    const response = await conversation.ask(message.text());
    console.log("response", response);
    await message.talker().say(response);
  }
}
// 处理 会员商品价格单独请求 价格接口
function getMoneyGoods(data) {
  if (!data) throw error;
  return new Promise(async (resolve, reject) => {
    const promise = data.list.map(async (item) => {
      return await getPrice(item.id);
    });
    const res = await Promise.all(promise);
    data.list.forEach((item) => {
      const goodsPriceInfo = res.find((i) => i.id === item.id);
      item.price = parseInt(goodsPriceInfo.price) + 1;
      item.sold = goodsPriceInfo.sold;
      item.status = goodsPriceInfo.status;
      item.stock = goodsPriceInfo.stock > 0 ? goodsPriceInfo.stock : "库存充足";
    });
    resolve(data);
  });
}
// 处理撤回的消息
async function getRecalled(message) {
  console.info("撤回message", message);
  console.info("撤回messageType", message.type());

  if (message.type() === message.Type.Recalled) {
    const recalledMessage = await message.toRecalled();
    console.info("收到撤回的消息：", recalledMessage.toString());
    writeToTxtFile(recalledMessage.toString());
  }
}

function writeToTxtFile(text, textName) {
  const timestamp = new Date().toLocaleString(); // 获取当前时间戳
  const dataToWrite = `------------\n${dayjs(timestamp).format(
    "YYYY-MM-DD HH:mm:ss"
  )}\n${text}\n`; // 构造需要写入的文本

  fs.access(`${textName}.txt`, fs.constants.F_OK, (err) => {
    if (err) {
      console.log("文件不存在，正在创建...");
      fs.writeFile("log.txt", dataToWrite, (err) => {
        if (err) throw err;
        console.log("文本已经写入到新文件");
      });
    } else {
      fs.appendFile("log.txt", dataToWrite, (err) => {
        if (err) throw err;
        console.log("文本已经追加到文件");
      });
    }
  });
}

module.exports = {
  dingDongBot,
  getMessagePayload,
  LOGPRE,
  writeToTxtFile,
  sellingMembership,
  chatGpt,
};
